import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SimpleBIOThreadHttpServer {
    public static void main(String[] args) {
        ExecutorService taskExecutor =
                new ThreadPoolExecutor(16, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1000000),
                        new ThreadPoolExecutor.DiscardPolicy());
        int port = 8081;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);
            Socket clientSocket;
            while (true) {
                clientSocket = serverSocket.accept();
                System.out.println("Accepted connection from " + clientSocket.getRemoteSocketAddress());

                // 创建一个线程来处理客户端请求
                taskExecutor.submit(new BioTread(clientSocket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class BioTread implements Runnable {
        private  Socket clientSocket;

        public BioTread(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        /**
         * 任务处理器
         */
        @Override
        public void run() {
            try (
                    InputStream inputStream = clientSocket.getInputStream();
                    OutputStream outputStream = clientSocket.getOutputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))
            ) {
                // 读取HTTP请求
                String line;
                StringBuilder request = new StringBuilder();
                while ((line = reader.readLine()) != null && !line.isEmpty()) {
                    request.append(line).append("\r\n");
                }
                System.out.println(request);
                // 处理HTTP请求，这里可以编写你的业务逻辑
                String httpResponse = "HTTP/1.1 200 OK\r\n\r\nHello, World!\r\n";
                writer.write(httpResponse);
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
